package com.chensi.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class MyInterceptor extends HandlerInterceptorAdapter
{
	private static final Logger log=Logger.getLogger(MyInterceptor.class);
	
	/**
	 * 不需要拦截的url
	 */
	private static final String[] IGNORE_URI = { "/user/doLogin.do", "/user/login.do" };


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		String url = request.getRequestURL().toString();
		//获取查询条件
		String queryString=request.getQueryString();
		log.info(">>> "+url);
		for (String s : IGNORE_URI)
		{
			if (url.contains(s))
			{
				return true;
			}
		}

		// 进行状态判断  权限，session等等
		HttpSession session = request.getSession(true);
		
		if(session.getAttribute("username")==null){
			log.warn("不存在session!!");
			session.setAttribute("beforeLogin", StringUtils.hasLength(queryString)?url+"?"+queryString:url);
			response.sendRedirect(request.getContextPath() + "/user/login.do");
			return false;
		}
		//登录后返回登录前页面
		if(session.getAttribute("beforeLogin")!=null){
			String beforeLoginUrl=session.getAttribute("beforeLogin").toString();
			session.removeAttribute("beforeLogin");
			response.sendRedirect(beforeLoginUrl);
		}
		return true;
	}

}
